package jsu.blogger.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jsu.blogger.util.DataFilterUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebFilter("/*")
@Order(2)
public class DataFilter extends BaseFilter {

    private static final Logger log = LoggerFactory.getLogger(DataFilter.class);

    @Override
    protected void doHttpFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 检查请求方法
        String method = httpServletRequest.getMethod();
        if (method.equalsIgnoreCase("GET")) {
//            System.out.println("GET请求不进行数据校验，放行");
            chain.doFilter(request, response);
            return;
        }
        String requestURI=httpServletRequest.getRequestURI();
        String basePath = requestURI.substring(0, requestURI.lastIndexOf("/"));
        //System.out.println(basePath);
        if(method.equalsIgnoreCase("POST")
                &&basePath.equalsIgnoreCase("/img")){
//            log.info("/img post请求不进行数据校验，放行");
            chain.doFilter(request, response);
            return;
        }
        if(method.equalsIgnoreCase("POST")
                &&(requestURI.contains("/live/getLive")||(requestURI.contains("/live/getRecommendLive")))){
            chain.doFilter(request, response);
            return;
        }
        // 放行 POST 请求到 /file/upload -----xu
        if (method.equalsIgnoreCase("POST") && requestURI.equalsIgnoreCase("/file/upload")) {
            log.info("/file/upload post请求不进行数据校验，放行");
            chain.doFilter(request, response);
            return;
        }
        // 处理非GET请求
        String requestBody = DataFilterUtil.readRequestBody(httpServletRequest);
        if (requestBody != null) {
            try {
                Map<String, Object> requestBodyMap = DataFilterUtil.parseRequestBody(requestBody);
                Map<String, Object> requestDataMap = (Map<String, Object>) requestBodyMap.get("data");

//                log.info(requestDataMap.toString());//打印接受到的请求体数据

                String msgType = (String) requestBodyMap.get("msgType"); // 假设请求体中包含messageType
                // 使用 DataFilterUtil 进行数据校验
                List<String> validationErrors = DataFilterUtil.validateData(msgType, requestDataMap);
                if (validationErrors.isEmpty()) {
                    httpServletRequest.setAttribute("requestBody", requestDataMap);
                    chain.doFilter(request, response);
                } else {
                    log.info("data缺少字段: " + validationErrors);
                    ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    response.setContentType("text/html;charset=utf-8");
                    response.getWriter().write(validationErrors.toString());
                }
            }catch (Exception e) {
                log.info(e.getMessage());
                log.error("前端发送数据格式不匹配，出现异常");
            }
        } else {
            log.info("请求体为空！请求驳回");
            ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("无效的请求数据: 请求体为空");
        }
    }
}
